package com.komon.object.header;

import java.util.HashMap;
import java.util.Map;

public class MediaType {
	private final String type;
	private final String subType;
	private final Map<String, String> attributes = new HashMap<String, String>();
	
	/**
	 *  media-type     = type "/" subtype *( ";" parameter )
       	type           = token
       	subtype        = token
       	parameter               = attribute "=" value
       	attribute               = token
       	value                   = token | quoted-string
	 * @param mediaType
	 */
	//TODO refactor
	public MediaType(String mediaType){
		int slash = mediaType.indexOf('/');
		this.type = mediaType.substring(0, slash);
		int semicolon = mediaType.indexOf(';');
		if (semicolon > 0) {
			this.subType = mediaType.substring(slash + 1, semicolon);
			String parameters = mediaType.substring(semicolon+1);
			
			int nextParameterIndex = parameters.indexOf(';');
			while(nextParameterIndex > 0) {
				String currentParameter = parameters.substring(nextParameterIndex);
				int equalIndex = currentParameter.indexOf('=');
				String attribure = currentParameter.substring(equalIndex);
				String value = currentParameter.substring(equalIndex + 1, currentParameter.length());
				attributes.put(attribure, value);
				
				nextParameterIndex = currentParameter.indexOf(';', nextParameterIndex);
			}
		} else {
			this.subType = mediaType.substring(slash + 1);
		}
	}

	/**
	 * @return the type
	 */
	public String getType() {
		return type;
	}
	/**
	 * @return the subType
	 */
	public String getSubType() {
		return subType;
	}

	public String getAttributeValue(String attribute){ 
		for (Map.Entry<String, String> entry : attributes.entrySet()) {
			if (entry.getKey().equalsIgnoreCase(attribute)) {
				return entry.getValue();
			}
		}
		return null;
	}
}	
